﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeRepositoryConsole.Algorithm
{
    class BubbleSort
    {
        private void PrintArrary(int[] arrary)
        {
            foreach (var item in arrary)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine("");
        }

        /// <summary>
        /// <seealso cref="http://www.geeksforgeeks.org/bubble-sort/"/>
        /// </summary>
        /// <param name="arrary"></param>
        public void Sort1(int[] arrary)
        {
            for (int i = 0; i < arrary.Length; i++)
                for (int j = 0; j < arrary.Length - 1 - i; j++)
                {
                    if (arrary[j] > arrary[j + 1])
                    {
                        int temp = arrary[j];
                        arrary[j] = arrary[j + 1];
                        arrary[j + 1] = temp;
                    }
                }

            PrintArrary(arrary);
        }

        /// <summary>
        /// <seealso cref="http://www.geeksforgeeks.org/bubble-sort/"/>
        /// </summary>
        /// <param name="array"></param>
        public void Sort1_Optimized(int[] array)
        {
            bool swapped = false;
            for (int i = 0; i < array.Length; i++)
            {
                for (int j = 0; j < array.Length - 1 - i; j++)
                {
                    if (array[j] > array[j + 1])
                    {
                        int temp = array[j];
                        array[j] = array[j + 1];
                        array[j + 1] = temp;
                        swapped = true;
                    }
                }

                if (swapped == false)
                {
                    break;
                }
            }

            PrintArrary(array);
        }

        /// <summary>
        /// <seealso cref="https://stackoverflow.com/questions/14768010/simple-bubble-sort-c-sharp"/>
        /// </summary>
        /// <param name="arrary"></param>
        public void Sort2(int[] arrary)
        {
            for (int i = 0; i < arrary.Length; i++)
                for (int j = 0; j < arrary.Length - 1; j++)
                {
                    if (arrary[j] > arrary[j + 1])
                    {
                        int temp = arrary[j];
                        arrary[j] = arrary[j + 1];
                        arrary[j + 1] = temp;
                    }
                }

            PrintArrary(arrary);
        }

        public void Test()
        {
            int[] unSort = { 2, 32, 43, 2, 99, 9, 10 };

            Console.WriteLine("UnSorted:");
            PrintArrary(unSort);

            Sort1(unSort);
            Sort1_Optimized(unSort);
            Sort2(unSort);
        }
    }
}
